<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/myblog/images/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblog/images/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblog/images/favicon-16x16.png">
  <link rel="mask-icon" href="/myblog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblog/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic%7CRoboto+Slab:300,300italic,400,400italic,700,700italic%7CNoto+Serif+SC:300,300italic,400,400italic,700,700italic%7CAmita:300,300italic,400,400italic,700,700italic%7CMontserrat:300,300italic,400,400italic,700,700italic%7CPT+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wang-chen1119.gitee.io","root":"/myblog/","images":"/myblog/images","scheme":"Pisces","darkmode":false,"version":"8.13.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":true,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/myblog/js/config.js"></script>

    <meta name="description" content="贪心算法1. 什么是贪心算法 所谓贪心算法就是在解决问题时，不去考虑全局最优解，而是在每一步都取当前的局部最优解。 即贪心算法总是在做目前看来最好的选择，所以贪心算法不能对所有问题都得到最优解。  2.举几个贪心算法的例子1. 分配问题">
<meta property="og:type" content="blog">
<meta property="og:title" content="贪心算法">
<meta property="og:url" content="http://wang-chen1119.gitee.io/myblog/2022/10/28/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95/index.html">
<meta property="og:site_name" content="Yorn&#39;s Notes">
<meta property="og:description" content="贪心算法1. 什么是贪心算法 所谓贪心算法就是在解决问题时，不去考虑全局最优解，而是在每一步都取当前的局部最优解。 即贪心算法总是在做目前看来最好的选择，所以贪心算法不能对所有问题都得到最优解。  2.举几个贪心算法的例子1. 分配问题">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229145924442.png">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229150634645.png">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229150824018.png">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229151537204.png">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229151914874.png">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229152543203.png">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229152614480.png">
<meta property="article:published_time" content="2022-10-28T08:46:25.656Z">
<meta property="article:modified_time" content="2022-10-28T08:46:14.283Z">
<meta property="article:author" content="yorn">
<meta property="article:tag" content="贪心算法">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://wang-chen1119.gitee.io/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229145924442.png">


<link rel="canonical" href="http://wang-chen1119.gitee.io/myblog/2022/10/28/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://wang-chen1119.gitee.io/myblog/2022/10/28/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95/","path":"2022/10/28/贪心算法/","title":"贪心算法"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>贪心算法 | Yorn's Notes</title>
  






  <noscript>
    <link rel="stylesheet" href="/myblog/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/myblog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Yorn's Notes</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-首页"><a href="/myblog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-关于"><a href="/myblog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-标签"><a href="/myblog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-分类"><a href="/myblog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95"><span class="nav-number">1.</span> <span class="nav-text">贪心算法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AF%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95"><span class="nav-number">1.0.1.</span> <span class="nav-text">1. 什么是贪心算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E4%B8%BE%E5%87%A0%E4%B8%AA%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95%E7%9A%84%E4%BE%8B%E5%AD%90"><span class="nav-number">1.0.2.</span> <span class="nav-text">2.举几个贪心算法的例子</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E5%88%86%E9%85%8D%E9%97%AE%E9%A2%98"><span class="nav-number">1.0.2.1.</span> <span class="nav-text">1. 分配问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8"><span class="nav-number">1.0.2.2.</span> <span class="nav-text">2.买卖股票</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-%E5%8A%A0%E6%B2%B9%E7%AB%99%E9%97%AE%E9%A2%98"><span class="nav-number">1.0.2.3.</span> <span class="nav-text">3.加油站问题</span></a></li></ol></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="yorn"
      src="/myblog/uploads/head.jpg">
  <p class="site-author-name" itemprop="name">yorn</p>
  <div class="site-description" itemprop="description">足够专注才能成功</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/myblog/archives/">
          <span class="site-state-item-count">53</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/myblog/categories/">
        <span class="site-state-item-count">13</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/myblog/tags/">
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wang-chen1119" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wang-chen1119" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:w1905989051@gmail.com" title="E-Mail → mailto:w1905989051@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>


  <div class="links-of-blogroll site-overview-item animated">
    <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://blog.csdn.net/qq_51088445" title="https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_51088445" rel="noopener" target="_blank">CSDN</a>
        </li>
    </ul>
  </div>

        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/wang-chen1119" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://wang-chen1119.gitee.io/myblog/2022/10/28/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/myblog/uploads/head.jpg">
      <meta itemprop="name" content="yorn">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Yorn's Notes">
      <meta itemprop="description" content="足够专注才能成功">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="贪心算法 | Yorn's Notes">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          贪心算法
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2022-10-28 16:46:25 / 修改时间：16:46:14" itemprop="dateCreated datePublished" datetime="2022-10-28T16:46:25+08:00">2022-10-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/myblog/categories/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">贪心算法</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>3.1k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>3 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="贪心算法"><a href="#贪心算法" class="headerlink" title="贪心算法"></a>贪心算法</h1><h3 id="1-什么是贪心算法"><a href="#1-什么是贪心算法" class="headerlink" title="1. 什么是贪心算法"></a>1. 什么是贪心算法</h3><blockquote>
<p>所谓贪心算法就是在解决问题时，不去考虑全局最优解，而是在每一步都取当前的局部最优解。</p>
<p>即贪心算法总是在做目前看来最好的选择，所以贪心算法不能对所有问题都得到最优解。</p>
</blockquote>
<h3 id="2-举几个贪心算法的例子"><a href="#2-举几个贪心算法的例子" class="headerlink" title="2.举几个贪心算法的例子"></a>2.举几个贪心算法的例子</h3><h4 id="1-分配问题"><a href="#1-分配问题" class="headerlink" title="1. 分配问题"></a>1. 分配问题</h4><p>来自[力扣](<a target="_blank" rel="noopener" href="https://leetcode-cn.com/">力扣（LeetCode）官网 - 全球极客挚爱的技术成长平台 (leetcode-cn.com)</a>)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/assign-cookies/">455. 分发饼干</a></p>
<p>假设你是一位很棒的家长，想要给你的孩子们一些小饼干。但是，每个孩子最多只能给一块饼干。</p>
<p>对每个孩子 <code>i</code>，都有一个胃口值 <code>g[i]</code>，这是能让孩子们满足胃口的饼干的最小尺寸；并且每块饼干 <code>j</code>，都有一个尺寸 <code>s[j]</code> 。如果 <code>s[j] &gt;= g[i]</code>，我们可以将这个饼干 <code>j</code> 分配给孩子 <code>i</code> ，这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子，并输出这个最大数值。</p>
<p><strong>示例 1:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">输入: g = [1,2,3], s = [1,1]</span><br><span class="line">输出: 1</span><br><span class="line">解释: </span><br><span class="line">你有三个孩子和两块小饼干，3个孩子的胃口值分别是：1,2,3。</span><br><span class="line">虽然你有两块小饼干，由于他们的尺寸都是1，你只能让胃口值是1的孩子满足。</span><br><span class="line">所以你应该输出1。</span><br></pre></td></tr></table></figure>

<p><strong>示例 2:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">输入: g = [1,2], s = [1,2,3]</span><br><span class="line">输出: 2</span><br><span class="line">解释: </span><br><span class="line">你有两个孩子和三块小饼干，2个孩子的胃口值分别是1,2。</span><br><span class="line">你拥有的饼干数量和尺寸都足以让所有孩子满足。</span><br><span class="line">所以你应该输出2.</span><br></pre></td></tr></table></figure>

<p><strong>解答</strong></p>
<p>这道题就是一道使用贪心算法的经典题目。</p>
<p>我们所说的局部最优即是将大的饼干喂给胃口大的孩子，充分利用饼干尺寸，最后得到全局最优(喂饱更多的小孩)</p>
<p><img src="/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229145924442.png" alt="image-20211229145924442"></p>
<p>所以可以写出代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">findContentChildren</span><span class="params">(<span class="type">int</span>[] g, <span class="type">int</span>[] s)</span> &#123;</span><br><span class="line">        <span class="comment">// 首先对两个数组进行排序</span></span><br><span class="line">        Arrays.sort(g);</span><br><span class="line">        Arrays.sort(s);</span><br><span class="line">        <span class="type">int</span> <span class="variable">start</span> <span class="operator">=</span> s.length-<span class="number">1</span>;</span><br><span class="line">        <span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> i=g.length-<span class="number">1</span>; start&gt;=<span class="number">0</span> &amp;&amp; i&gt;=<span class="number">0</span>; i--)&#123;</span><br><span class="line">            <span class="comment">//从大到小进行比较</span></span><br><span class="line">            <span class="keyword">if</span>( s[start]&gt;=g[i])&#123;</span><br><span class="line">                start--;</span><br><span class="line">                count++;</span><br><span class="line">            &#125;</span><br><span class="line"> </span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> count;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-买卖股票"><a href="#2-买卖股票" class="headerlink" title="2.买卖股票"></a>2.买卖股票</h4><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/">122. 买卖股票的最佳时机 II</a></p>
<p>给定一个数组 <code>prices</code> ，其中 <code>prices[i]</code> 是一支给定股票第 <code>i</code> 天的价格。</p>
<p>设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易（多次买卖一支股票）。</p>
<p><strong>注意：</strong>你不能同时参与多笔交易（你必须在再次购买前出售掉之前的股票）。</p>
<p><strong>示例 1:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">输入: prices = [7,1,5,3,6,4]</span><br><span class="line">输出: 7</span><br><span class="line">解释: 在第 2 天（股票价格 = 1）的时候买入，在第 3 天（股票价格 = 5）的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。</span><br><span class="line">     随后，在第 4 天（股票价格 = 3）的时候买入，在第 5 天（股票价格 = 6）的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。</span><br></pre></td></tr></table></figure>

<p><strong>示例 2:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">输入: prices = [1,2,3,4,5]</span><br><span class="line">输出: 4</span><br><span class="line">解释: 在第 1 天（股票价格 = 1）的时候买入，在第 5 天 （股票价格 = 5）的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。</span><br><span class="line">     注意你不能在第 1 天和第 2 天接连购买股票，之后再将它们卖出。因为这样属于同时参与了多笔交易，你必须在再次购买前出售掉之前的股票。</span><br></pre></td></tr></table></figure>

<p><strong>示例 3:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">输入: prices = [7,6,4,3,1]</span><br><span class="line">输出: 0</span><br><span class="line">解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。</span><br></pre></td></tr></table></figure>

<p><strong>解答</strong></p>
<p>此题也能够使用贪心算法解决</p>
<p><img src="/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229150634645.png" alt="image-20211229150634645"></p>
<p>我们只去考虑每天能获得的利润及：</p>
<p><img src="/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229150824018.png" alt="image-20211229150824018"></p>
<p>然后我们贪心所贪的就是所有的正利润即 4+3 &#x3D; 7也就是我们最后的整体最优解</p>
<p>最后的代码为</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">maxProfit</span><span class="params">(<span class="type">int</span>[] prices)</span> &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">result</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="comment">//这里注意的是我们是从第二天开始找利润的</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">1</span>; i&lt;prices.length; i++)&#123;</span><br><span class="line">            result += Math.max(prices[i]-prices[i-<span class="number">1</span>],<span class="number">0</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-加油站问题"><a href="#3-加油站问题" class="headerlink" title="3.加油站问题"></a>3.加油站问题</h4><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/gas-station/">134. 加油站</a></p>
<p>在一条环路上有 <em>N</em> 个加油站，其中第 <em>i</em> 个加油站有汽油 <code>gas[i]</code> 升。</p>
<p>你有一辆油箱容量无限的的汽车，从第 <em>i</em> 个加油站开往第 <em>i+1</em> 个加油站需要消耗汽油 <code>cost[i]</code> 升。你从其中的一个加油站出发，开始时油箱为空。</p>
<p>如果你可以绕环路行驶一周，则返回出发时加油站的编号，否则返回 -1。</p>
<p><strong>说明:</strong> </p>
<ul>
<li>如果题目有解，该答案即为唯一答案。</li>
<li>输入数组均为非空数组，且长度相同。</li>
<li>输入数组中的元素均为非负数。</li>
</ul>
<p><strong>示例 1:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">输入: </span><br><span class="line">gas  = [1,2,3,4,5]</span><br><span class="line">cost = [3,4,5,1,2]</span><br><span class="line"></span><br><span class="line">输出: 3</span><br><span class="line"></span><br><span class="line">解释:</span><br><span class="line">从 3 号加油站(索引为 3 处)出发，可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油</span><br><span class="line">开往 4 号加油站，此时油箱有 4 - 1 + 5 = 8 升汽油</span><br><span class="line">开往 0 号加油站，此时油箱有 8 - 2 + 1 = 7 升汽油</span><br><span class="line">开往 1 号加油站，此时油箱有 7 - 3 + 2 = 6 升汽油</span><br><span class="line">开往 2 号加油站，此时油箱有 6 - 4 + 3 = 5 升汽油</span><br><span class="line">开往 3 号加油站，你需要消耗 5 升汽油，正好足够你返回到 3 号加油站。</span><br><span class="line">因此，3 可为起始索引。</span><br></pre></td></tr></table></figure>

<p><strong>示例 2:</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">输入: </span><br><span class="line">gas  = [2,3,4]</span><br><span class="line">cost = [3,4,3]</span><br><span class="line"></span><br><span class="line">输出: -1</span><br><span class="line"></span><br><span class="line">解释:</span><br><span class="line">你不能从 0 号或 1 号加油站出发，因为没有足够的汽油可以让你行驶到下一个加油站。</span><br><span class="line">我们从 2 号加油站出发，可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油</span><br><span class="line">开往 0 号加油站，此时油箱有 4 - 3 + 2 = 3 升汽油</span><br><span class="line">开往 1 号加油站，此时油箱有 3 - 3 + 3 = 3 升汽油</span><br><span class="line">你无法返回 2 号加油站，因为返程需要消耗 4 升汽油，但是你的油箱只有 3 升汽油。</span><br><span class="line">因此，无论怎样，你都不可能绕环路行驶一周。</span><br></pre></td></tr></table></figure>



<p><strong>解答</strong></p>
<p>首先我们可以将此题用图表示出来</p>
<p><img src="/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229151537204.png" alt="image-20211229151537204"></p>
<p>关于此题我们首先要知道的是，每站的剩余油量的和如果是小于零的话，那么是无法绕环路行驶一周的。</p>
<p><img src="/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229151914874.png" alt="image-20211229151914874"></p>
<p>如上图可得 -2+ -2 + -2 + 3 + 3 &#x3D; 0；说明能够绕路行驶一周。</p>
<p>然后就是去确定起点，从第一个站开始，如果这个站的剩余油量是小于0的那么我们就需要令这个站的下个站为起点</p>
<p><img src="/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229152543203.png" alt="image-20211229152543203"></p>
<p><img src="/myblog/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95.assets/image-20211229152614480.png" alt="image-20211229152614480"></p>
<p>此题的局部最优为在区间[i,j]内，剩余油量的累加是小于0零的，那么起点为j+1</p>
<p>以上题来说，以索引为3的站为起点，到最后索引为5的站时剩余油量为6，因为我们判断了一定能够绕路一圈，所以我们可以确定剩余油量一定能够支持回到起点，而我们进行验证</p>
<p>6 -2 -2-2 &#x3D; 0，也证实了我们的想法。</p>
<p>代码实现为:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">canCompleteCircuit</span><span class="params">(<span class="type">int</span>[] gas, <span class="type">int</span>[] cost)</span> &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">start</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="type">int</span> <span class="variable">cur</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="type">int</span> <span class="variable">total</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">0</span>; i&lt; gas.length; i++)&#123;</span><br><span class="line">            cur += gas[i] - cost[i];</span><br><span class="line">            total += gas[i] - cost[i];</span><br><span class="line">            <span class="comment">//剩余油量小于0，起点取i+1,更新当前剩余油量</span></span><br><span class="line">            <span class="keyword">if</span>(cur &lt; <span class="number">0</span>)&#123;</span><br><span class="line">                start =i + <span class="number">1</span>;</span><br><span class="line">                cur = <span class="number">0</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; </span><br><span class="line">        <span class="comment">//如果剩余油量和小于0，那么一定不能绕路一圈</span></span><br><span class="line">        <span class="keyword">if</span>(total &lt; <span class="number">0</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> start;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>yorn
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://wang-chen1119.gitee.io/myblog/2022/10/28/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95/" title="贪心算法">http://wang-chen1119.gitee.io/myblog/2022/10/28/贪心算法/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/myblog/tags/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95/" rel="tag"><i class="fa fa-tag"></i> 贪心算法</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/myblog/2022/10/28/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95%E8%A7%A3%E5%86%B3%E5%8A%9B%E6%89%A3406%20452%E4%B8%A4%E9%A2%98/" rel="prev" title="贪心算法解题记录">
                  <i class="fa fa-chevron-left"></i> 贪心算法解题记录
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/myblog/2022/10/28/%E6%B5%8F%E8%A7%88%E5%99%A8%E8%BE%93%E5%85%A5%E4%B8%80%E4%B8%AAurl%E5%88%B0%E6%95%B4%E4%B8%AA%E9%A1%B5%E9%9D%A2%E6%98%BE%E7%A4%BA%E5%87%BA%E6%9D%A5%E7%BB%8F%E5%8E%86%E4%BA%86%E5%93%AA%E4%BA%9B%E8%BF%87%E7%A8%8B/" rel="next" title="浏览器输入一个url到整个页面显示出来经历了哪些过程">
                  浏览器输入一个url到整个页面显示出来经历了哪些过程 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yorn</span>
</div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/myblog/js/comments.js"></script><script src="/myblog/js/utils.js"></script><script src="/myblog/js/motion.js"></script><script src="/myblog/js/next-boot.js"></script><script src="/myblog/js/bookmark.js"></script>

  





  





<script src="/myblog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
